package com.youlu.campus.starter.sms.config;

import com.youlu.campus.starter.sms.properties.SmsOkHttpClientPoolProperties;
import lombok.Data;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Data
@Configuration
public class OkHttpClientConfig {

    @Autowired
    private SmsOkHttpClientPoolProperties poolProperties;

    /**
     * 创建okhttp连接客户端
     *
     * @return
     */
    @Bean(name = "smsOkHttpClient")
    public OkHttpClient getOkHttpClient() {
        //连接池
        ConnectionPool connectionPool = getConnectionPool();
        //重试拦截器
        ErrorRetryInterceptor retryInterceptor = getRetryInterceptor();
        //创建客户端
        return new OkHttpClient.Builder()
                .connectionPool(connectionPool) // 小连接池
                .connectTimeout(poolProperties.getConnectTimeout(), TimeUnit.SECONDS)  // 长超时
                .readTimeout(poolProperties.getReadTimeout(), TimeUnit.SECONDS)
                .addInterceptor(retryInterceptor) // 最大重试3次
                .build();
    }

    /**
     * 创建连接池
     *
     * @return
     */
    private ConnectionPool getConnectionPool() {
        return new ConnectionPool(poolProperties.getMaxConnections(), poolProperties.getKeepAliveDuration(), TimeUnit.SECONDS);
    }

    /**
     * 创建 重试拦截器
     *
     * @return
     */
    private ErrorRetryInterceptor getRetryInterceptor() {
        return new ErrorRetryInterceptor(poolProperties.getMaxRetries(), poolProperties.getRetrySleepTime());
    }

}